/**
 * 
 */
;(function(){
	var selectedTab = null,
	libsList,
	template, listItem, logo, name, version;
	
	/**
	 * initialize the template
	 */
	function initializeTemplate() {
		libsList = document.getElementById("list");
		template = document.querySelector("ul#template li.lib");
		logo = document.querySelector("ul#template div.logo img");
		name = document.querySelector("ul#template div.name");
		version = document.querySelector("ul#template sub.version");
	}
	
	function clearTemplate() {
		logo.removeAttribute("src");
		name.innerText = version.innerText = "";
	}
	
	function getDetectedLibs(){
		
		return localStorage[selectedTab.id] ? JSON.parse(localStorage[selectedTab.id]) : "";
	}
	
	/**
	 * 
	 */
	function addLibs(){
		var libsObj = getDetectedLibs(),
			lib,
			fragment = document.createDocumentFragment(),
			item;
		
		if (libsObj.constructor === Object){
			initializeTemplate();
			
			for (lib in libsObj){
				if (libsObj[lib].icon) {
					logo.src = "/images/libraries/" + libsObj[lib].icon + ".png";
				}
				name.innerText = lib;
				if (libsObj[lib].version) {
					version.innerText = chrome.i18n.getMessage("libVersion") + ": " + libsObj[lib].version;
				} else {
					version.innerHTML = "&nbsp;";
				}
				item = template.cloneNode(true);
				fragment.appendChild(item);
				
				//clean up the template before reuse it again
				clearTemplate();
			}
			libsList.appendChild(fragment);
		}
	}
	
	/**
	 * 
	 */
	function pageLoad(){
		chrome.tabs.getSelected(null, function(tab) {
			selectedTab = tab;
			addLibs();
		});
	}
	
	/**
	 * 
	 */
	window.addEventListener("load", pageLoad, false);
})();